const router = require('express').Router();
const { dbQuery, dbError, updateToken, sqlStrQuotationHandle } = require('../../tools');
const vertoken = require('../../token');
const { client, store } = require('../../redis');



const expressJwt = require('express-jwt');
//解析token获取用户信息
router.use(function (req, res, next) {
	const token = req.headers['authorization'];
    if (token == undefined) {
        next();
    } else {
        vertoken.getToken(token).then((data) => {
			req.data = data;
            next();
        }).catch((err) => {
            next();
        });
    }
});
//验证token是否过期并规定那些路由不需要验证
router.use(expressJwt({
    secret: vertoken.tokenScrect,
   // 算法
    algorithms: ['HS256']
})
.unless({
    path: ['/user', '/user/all', '/user/login', '/user/logout', '/user/register']  //不需要验证的接口名称
}));
//token失效返回信息
router.use(function (err, req, res, next) {
	console.log(err, 'token失效')
    if (err.status == 401) {
        return res.status(401).send({message: 'token失效'})
        //可以设置返回json 形式  res.json({message:'token失效'})
    }
});


router.get('/', function(req, res) {
	const {id} = req.query;
	dbQuery(`select id,account,name,gender,introduction,avator 
		from user_table
		where id='${id}'`)
	.then(data => {
		if (data.length < 1) {
			res.send({code: 0, message: '此用户不存在'})
			return;
		}
		res.send({code: 1, message: '获取成功', data: data[0]});
	})
	.catch(err => {
		dbError(res, err);
	});
});
router.get('/all', function(_, res) {
	dbQuery(`select id,account,name,gender,introduction,avator from user_table`)
	.then(data => {
		res.send({code: 1, message: '获取成功', data});
	})
	.catch(err => {
		dbError(res, err);
	});
});
router.post('/login', function(req, res) {
	// 加一个cookie登录

	let {account, password, remember} = req.body;
	account = req.session.account ? req.session.account : account;
	password = req.session.password ? req.session.password : password;

	if (!account || !password) {
		res.send({code: 0, message: '参数错误'});
		return;
	}

	const accountStr = sqlStrQuotationHandle(account);
	const passwordStr = sqlStrQuotationHandle(password);

	dbQuery(`select id,account,name,gender,introduction,avator,can_create 
		from user_table
		where binary account='${accountStr}' and binary password='${passwordStr}'`)
	.then(data => {
		if (data.length < 1) {
			res.send({code: 0, message: '用户名或密码错误'});
			return;
		}
		let sendObj = {code: 1,message: '登录成功', data: data[0]};

		let user_id = data[0].id;
		client.get(user_id, function(err, sid) {
			if (err) {
				console.log('redis error', err);
				return;
			}
			const socketio = require('../../socket');


			if (
				sid !== req.session.id && 
				socketio().connectUser && 
				socketio().connectUser[user_id] && 
				socketio().connectUser[user_id].length > 0
			) {
				// 此账号已经登录,且再次登录的位置不是相同浏览器,则将前一个登录位置退出登录

				// 使用sessionid 将 session清除
				store.destroy(sid, function(err) {
					if (err) {
						return;		
					}
					socketio().toEmit('quitLog', socketio().connectUser[user_id], {message: '你的账号在别处登录'})
				});
			}
			
			client.set(user_id, req.session.id);
			client.expire(user_id, remember ? 3600 * 24 * 7 : 3600 * 2);
		});


		req.session.account = account;
		req.session.password = password;

		if (remember) {
			return updateToken(res, data[0], sendObj);
		}
		// 不记住账号重新设置cookie时长
		req.session.cookie.expires = new Date(Date.now() + 3600 * 2000);
		req.session.cookie.maxAge = 3600 * 2000;
		req.session.touch();
		
		res.send(sendObj);
	})
	.catch(err => {
		dbError(res, err);
	});
});
router.get('/logout', function(req, res) {
	const {user_id} = req.query;
	req.session.destroy(function(err) {
		if (err) {
			res.send({code: 0, message: '退出登录失败'});
			return;		
		}
		client.expire(user_id, -1);
		res.send({code: 1, message: '退出登录'});
	});
});
router.post('/register', function(req, res) {
	const {account,password,gender,introduction,username} = req.body;
	const accountStr = sqlStrQuotationHandle(account);
	const passwordStr = sqlStrQuotationHandle(password);
	const introductionStr = sqlStrQuotationHandle(introduction);
	const usernameStr = sqlStrQuotationHandle(username);

	dbQuery(`insert into user_table
		(account,password,gender,introduction,name) 
		values
		('${accountStr}','${passwordStr}','${gender}','${introductionStr}','${usernameStr}')`)
		.then(() => {
			res.cookie('name', account, {signed: true, maxAge: 1000 * 60 * 10});
			res.cookie('pwd', password, {signed: true, maxAge: 1000 * 60 * 10});
			res.send({code: 1, message: '注册成功'});
		})
		.catch(err => {
			dbError(res, err);
		});
});

module.exports = router;